package cn.sycoder.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RedisService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    public void incrementLoginCount(String username) {
        // 使用以"user_login_counts"为键的哈希结构来存储用户登录次数
        redisTemplate.opsForHash().increment("user_login_counts", username, 1);
    }

    public List<Map.Entry<String, Long>> getTop5LoginUsers() {
//        Set<String> keys = redisTemplate.keys("user_login_counts*");
        Map<Object, Object> userLoginMap = redisTemplate.opsForHash().entries("user_login_counts");
        Map<String, Long> loginCounts = new HashMap<>();
        for (Map.Entry<Object, Object> entry : userLoginMap.entrySet()) {
            String username = (String) entry.getKey();
            Long count = (Long) entry.getValue(); // 这里假设值已经是 Long 类型
            loginCounts.put(username, count);
        }

        return loginCounts.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .limit(5)
                .collect(Collectors.toList());
    }
}